library(haven)
library(ggplot2);library(dplyr)
library(directlabels)
dir.create("tables")
dir.create("figures")
eb_data <- read_dta("EB1976_2023_All_v4.dta")

# Create proeu2: binary indicator for proeu==3
eb_data <- eb_data |> 
  mutate(
    proeu2 = ifelse(proeu == 3, 1, 0),
    
    # Create squared terms
    AGE2 = AGE^2,
    left_right2 = left_right^2,
    
    # Create ideological categories
    radleft = ifelse(left_right == 1, 1, 0),
    cleft = ifelse(left_right %in% c(2, 3, 4), 1, 0),
    centre = ifelse(left_right %in% c(5, 6), 1, 0),
    cright = ifelse(left_right %in% c(7, 8, 9), 1, 0),
    radright = ifelse(left_right == 10, 1, 0),
    
    # Create ideol_type categorical variable
    ideol_type = case_when(
      radleft == 1 ~ 1,
      cleft == 1 ~ 2,
      centre == 1 ~ 3,
      cright == 1 ~ 4,
      radright == 1 ~ 5,
      TRUE ~ 0)
  )

# Convert to factor with labels
eb_data$ideol_type <- factor(eb_data$ideol_type,
                             levels = 0:5,
                             labels = c("Missing", "lr= 1", "lr= 2,3,4", 
                                        "lr= 5,6", "lr= 7,8,9", "lr=10"))
## Figure 1
ggplot(eb_data, aes(YEAR, proeu2)) +
  geom_smooth(method="gam", aes(color = factor(ideol_type))) +
  geom_smooth(method="gam", linetype = "dashed", color = "gray35", se = FALSE) +
  labs(x = "", y = "Probability of supporting the EU") +
  scale_color_manual(values = c("lr= 1" = "red4", "lr= 2,3,4" = "red", "lr= 5,6" = "gold", "lr= 7,8,9" = "blue", "lr=10" = "purple4")) +
  guides(color = guide_legend(title = ("Left-Right position"))) +
  theme_minimal()
ggsave("figures/left-right_groups_nonlinear.png",
       width = 6, height = 4, units = "in", dpi = 450)